'use strict'

const { Blog, Op } = require('../model');

// get 方法
let fn_get = async (ctx, next) => {
    let keyword = ctx.request.query.keyword || '';
    if (keyword) {
        let list = await Blog.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? -1 : parseInt(keyword) },
                    { title: { [Op.like]: `%${keyword}%` } },
                    { digest: { [Op.like]: `%${keyword}%` } },
                    { text: { [Op.like]: `%${keyword}%` } },
                    { classify: { [Op.like]: `%${keyword}%` } },
                    { author: { [Op.like]: `%${keyword}%` } },
                ]
            },
            order: ['id']
        })
        ctx.body = list;
    } else {
        let list = await Blog.findAll({ order: ['id'] });
        ctx.body = list;
    }
}

// post 方法
let fn_post = async (ctx, next) => {
    let obj = ctx.request.body;
    Blog.create(obj);
    ctx.body = '添加成功'
}

// put 方法
let fn_put = async (ctx, next) => {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    Blog.update(obj, {
        where: {
            id: id
        }
    })
    ctx.body = '修改成功'
}

// delete 方法
let fn_delete = async (ctx, next) => {
    let id = ctx.request.params.id;
    Blog.destroy({ where: { id: id } })
    ctx.body = '删除成功'
}

module.exports = {
    'get /blog': fn_get,
    'post /blog': fn_post,
    'put /blog/:id': fn_put,
    'delete /blog/:id': fn_delete,
}